using System;
using System.Collections.Generic;
using System.Linq;
using TLDRML.Tokens;

namespace TLDRML.Nodes
{
    public class ElementNode : ParentNode, IHasAttributes
    {
        public string Type { get; set; }
        public ICollection<AttributeNode> AttributeNodes { get; private set; }

        public ElementNode() : this(null, (Node[])null)
        {
        }

        public ElementNode(params Node[] childNodes) : this (null, childNodes)
        {
        }

        public ElementNode(string type, params Node[] childNodes) : base(childNodes)
        {
            Type = type;
            AttributeNodes = new List<AttributeNode>();
        }

        public override IEnumerable<Token> Parse(IEnumerable<Token> tokens)
        {
            tokens = Expect<LiteralToken>(tokens, t => Type = t.Value);

            while (!(tokens.First() is NewLineToken))
                tokens = Parse<AttributeNode>(tokens, AddAttribute);

            tokens = Expect<NewLineToken>(tokens, DiscardToken);

            if (tokens.FirstOrDefault() is IndentToken)
            {
                tokens = Expect<IndentToken>(tokens, DiscardToken);

                while (!(tokens.First() is OutdentToken))
                    tokens = Parse<ElementNode>(tokens, AddChild);

                tokens = Expect<OutdentToken>(tokens, DiscardToken);
            }

            return tokens;
        }

        public void AddAttribute(AttributeNode attr)
        {
            if (attr == null)
                throw new ArgumentNullException("attr");

            AttributeNodes.Add(attr);
        }

        public bool Equals(ElementNode other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.Type, Type);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (ElementNode)) return false;
            return Equals((ElementNode) obj);
        }

        public override int GetHashCode()
        {
            return (Type != null ? Type.GetHashCode() : 0);
        }
    }
}